<template>
  <div class="app-container">
    <div class="table-box">
      <!-- 搜索区 开始 -->
      <div class="search-box">
        <el-form ref="listQuery" :model="listQuery" label-width="90px">
          <el-row>
            <el-col :xs="24" :sm="20" :md="20" :lg="20" :xl="20">
              <el-row>
                <!-- 表单元素 开始 -->
                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                  <el-form-item
                    :label="$t('common.status')"
                    prop="status"
                    class="select-class"
                  >
                    <el-select
                      v-model="listQuery.status"
                      :placeholder="$t('common.pleaseSelect')"
                      clearable
                    >
                      <el-option
                        v-for="item in dictionaryService.getItems('statusVar')"
                        :key="item.id"
                        :label="item.name"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                  <el-form-item :label="$t('common.keywords')" prop="keywords_value">
                    <el-input
                      v-model="listQuery.keywords_value"
                      :placeholder="$t('common.pleaseEnter')+$t('common.keywords')"
                      class="input-with-select"
                      clearable
                      @keyup.enter.native="handleFilter"
                    >
                      <el-select
                        slot="prepend"
                        v-model="listQuery.keywords_key"
                        :placeholder="$t('common.pleaseSelect')"
                        style="width: 90px"
                      >
                        <el-option
                          v-for="item in keywordsKeyOptions"
                          :key="item.id"
                          :label="item.text"
                          :value="item.id"
                        />
                      </el-select>
                    </el-input>
                  </el-form-item>
                </el-col>
                <!-- 表单元素 开始 -->
              </el-row>
            </el-col>
            <el-col :xs="24" :sm="4" :md="4" :lg="4" :xl="4" class="search-btn">
              <el-button
                v-waves
                type="primary"
                icon="el-icon-search"
                @click="handleFilter"
              >
                {{ $t('common.search') }}
              </el-button>
              <el-button icon="el-icon-refresh" @click="handleResetFilter">{{ $t('common.reset') }}</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 搜索区 结束 -->

      <!-- 按钮功能区 开始 -->
      <el-row :gutter="10" class="btn-box">
        <el-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="24"
          :xl="24"
          class="btnfunction-section-col"
        >
          <el-button type="primary" icon="el-icon-plus" :disabled="!checkPermission(['admin.ads.store'])" @click="handleCreate()">{{
            $t('common.create')
          }}</el-button>
          <el-button
            plain
            type="danger"
            icon="el-icon-delete"
            :disabled="!checkPermission(['admin.ads.destroy'])"
            @click="handleAllDelete()"
          >
            {{ $t('common.delete') }}
          </el-button>
          <el-button type="primary" icon="awesome-icon fas fa-sort" :disabled="!checkPermission(['admin.ads.updateStore'])" @click="handleUpdateSort()">
            {{ $t('common.updateSort') }}
          </el-button>
          <el-button icon="awesome-icon fas fa-step-backward" @click="handleBack"> {{ $t('common.back') }}</el-button>
        </el-col>
      </el-row>
      <!-- 按钮功能区 结束 -->

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
        max-height="540"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" fixed="left" />
        <el-table-column
          label="ID"
          prop="id"
          sortable="custom"
          align="center"
          width="80"
          :class-name="getSortClass('id')"
        >
          <template slot-scope="{ row }">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.name')" min-width="150px">
          <template slot-scope="{ row }"> {{ row.name }} </template>
        </el-table-column>
        <el-table-column
          v-if="adsSpace.type==1"
          :label="$t('ads.cover_image')"
          align="center"
          width="150"
        >
          <template slot-scope="{ row }">
            <el-image
              v-if="row.cover_image.length>0"
              style="height: 90px; width: 90px"
              :src="row.cover_image.length>0 ? row.cover_image[0].url : ''"
              fit="cover"
              :preview-src-list="row.cover_image.map((item)=>{return item.url})"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.href')" align="center" width="150">
          <template slot-scope="{ row }">
            {{ row.href }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('ads.cast_time')"
          align="center"
          min-width="150"
        >
          <template slot-scope="{ row }">
            {{ row.cast_period==1?$t('ads.cast_period1'):row.start_time +" "+ $t('common.rangeTo') +" "+ row.end_time }}
          </template>
        </el-table-column>
        <el-table-column width="180" :label="$t('common.sort')" prop="sort" align="center" sortable="custom" :class-name="getSortClass('sort')">
          <template slot-scope="{ row }">
            <el-input-number v-model="row.sort" controls-position="right" :min="1" />
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.status')"
          class-name="status-col"
          width="100"
        >
          <template slot-scope="{ row }">

            <el-switch
              v-model.number="row.status"
              :active-value="1"
              :inactive-value="0"
              :disabled="!checkPermission(['admin.ads.updateStatus'])"
              @change="handleModifyStatus($event,row)"
            />

          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.created_at')"
          width="200"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.created_at }}</span>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.operation')"
          align="center"
          width="150"
          class-name="small-padding fixed-width"
          fixed="right"
        >
          <template slot-scope="{ row, $index }">
            <el-link
              type="primary"
              :underline="false"
              :disabled="!checkPermission(['admin.ads.update'])&&!checkPermission(['admin.ads.show'])"
              icon="el-icon-edit"
              :title="$t('common.edit')"
              @click="handleEdit(row)"
            >{{ $t('common.edit') }}
            </el-link>&nbsp;
            <el-link
              type="primary"
              :underline="false"
              :disabled="!checkPermission(['admin.ads.destroy'])"
              icon="el-icon-delete"
              :title="$t('common.delete')"
              @click="handleDelete(row, $index)"
            >{{ $t('common.delete') }}
            </el-link>&nbsp;
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 开始 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
      <!-- 分页功能 结束 -->
    </div>
  </div>
</template>

<script>
import { index, updateStatus, destory, updateSort } from '@/api/ads'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getAdsSpaceConfig } from '@/api/ads-space'
import checkPermission from '@/utils/permission'

export default {
  name: 'AdsIndex',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        sort: '+sort',
        status: '',
        keywords_key: 'name',
        keywords_value: ''
      },
      keywordsKeyOptions: [{ id: 'name', text: this.$t('common.name') }],
      multipleSelection: [],
      // 路由参数
      routerParams: {},
      // 广告位标识
      space_id: 0,
      adsSpace: {}
    }
  },
  created() {
    this.routerParams = this.$route.params
    this.space_id = this.routerParams.space_id
    this.getList()
  },
  methods: {
    checkPermission,
    async getList() {
      this.listLoading = true
      await index(this.space_id, this.listQuery).then((response) => {
        this.list = response.data.items
        this.total = response.data.meta.total
      }).catch(() => {
        this.closeBack()
      })
      await getAdsSpaceConfig(this.space_id).then((response) => {
        this.adsSpace = response.data
      }).catch(() => {
        this.closeBack(this.back_route_name, this.back_route_params)
      })
      this.listLoading = false
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleResetFilter() {
      this.listQuery.page = 1
      this.$refs['listQuery'].resetFields()
      this.getList()
    },
    handleModifyStatus($event, row) {
      updateStatus(this.space_id, row.id, { status: $event }).then((response) => {
        this.$message.success(response.message)
        row.status = $event
      }).catch(() => {
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (order === 'ascending') {
        this.listQuery.sort = '+' + prop
      } else if (order === 'descending') {
        this.listQuery.sort = '-' + prop
      } else {
        this.listQuery.sort = ''
      }
      this.listQuery.sort && this.handleFilter()
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      if (sort === `+${key}`) {
        return 'ascending'
      } else if (sort === `-${key}`) {
        return 'descending'
      } else {
        return ''
      }
    },
    handleDelete(row, index) {
      this.$confirm(this.$t('common.delete_confirm_tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      })
        .then(() => {
          destory(this.space_id, row.id).then((response) => {
            this.$message.success(response.message)
            this.list.splice(index, 1)
          }).catch(() => {
          })
        })
        .catch(() => {
          this.$message.info(this.$t('common.canceled'))
        })
    },
    handleUpdateSort() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('common.please_choose_sort_tips'))
        return
      }
      const params = this.multipleSelection.map((e) => {
        return { id: e.id, sort: e.sort }
      })
      updateSort(this.space_id, { sort: params }).then((response) => {
        this.$message.success(response.message)
        this.getList()
      }).catch(() => {
      })
    },
    handleCreate() {
      this.$router.push({ name: 'AdsCreate' })
    },
    handleEdit(row) {
      this.$router.push({ name: 'AdsEdit', params: { space_id: this.space_id, id: row.id }})
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleAllDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('common.delete_items_tips'))
        return
      }
      this.$confirm(
        this.$t('common.delete_confirm_tips'),
        this.$t('common.warm_tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          const ids = this.multipleSelection.map(function(e) {
            return e.id
          })
          destory(this.space_id, ids).then((response) => {
            this.$message.success(response.message)
            this.getList()
          }).catch(() => {
          })
        })
        .catch(() => {
          this.$message.info(this.$t('common.canceled'))
        })
    },
    handleBack() {
      this.closeBack('AdsSpace')
    }
  }
}
</script>
<style scoped  lang="scss" >
</style>
